package JZOffer;

import java.util.HashMap;

/**
 * @author Lw中
 * @date 2021/9/22 14:23
 */
public class Jz35 {

    // Jz35.复杂链表的复制
    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    public Node copyRandomList(Node head) {
//        Node cur = head;
//        Node dum = new Node(0), pre = dum;
//        while (cur != null) {
//            Node node = new Node(cur.val);
//            pre.next = node;
//            //
//            cur = cur.next;
//            pre = node;
//        }
        // 使用哈希表存储节点
        Node cur = head;
        HashMap<Node, Node> map = new HashMap<>();
        while (cur != null) {
            map.put(cur, new Node(cur.val));
            cur = cur.next;
        }
        cur = head;
        while (cur != null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }

}
